package com.vshop.service.impl;

import com.vshop.config.dto.StringOutputConstant;
import com.vshop.entity.agatewaytobeijing.queryh5order.response.H5PackageOrder;
import com.vshop.entity.alast.common.ServicePlanOrderRecord;
import com.vshop.entity.callback.request.RequestResultCallback;
import com.vshop.entity.comentity.OrderExceptionRecord;
import com.vshop.mapper.PurchaseLogicMapper;
import com.vshop.utils.mail.SendMailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * 真正的订购套餐的逻辑梳理公共类
 * <p>
 * 订购套餐的操作（可能是新购套餐，也有可能是续订套餐）
 *
 * @author lm
 * @date 2020/1/7
 */

@Service("purchaseService")
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class PurchaseLogicService {
    @Resource
    private PurchaseLogicMapper purchaseMapper;
    @Autowired
    JavaMailSenderImpl javaMailSender;
    @Value("${spring.profiles.active}")
    private String active;

    /**
     * 当【新订|续订】回调的结果是非成功（0000）的情况时发送邮件
     * 【新订|续订】回调 异常发到 service@linksfield.net
     *
     * @param callback
     * @param record
     */
    public void sendMailForCallback(RequestResultCallback callback, ServicePlanOrderRecord record, String type) {
        try {
            String sendText = "卡片iccId：" + callback.getDeviceCode() + "\n" +
                    "套餐编码：" + record.getPackageCode() + "\n" +
                    "套餐名称：" + record.getPackageName() + "\n" +
                    "订购周期：" + record.getOrderPeriod() + "\n" +
                    "操作类型：" + type + "\n" +
                    "订单号：" + callback.getOrderId() + "\n" +
                    "返回码：" + callback.getCode() + "\n" +
                    "异常描述：" + callback.getMessage() + "\n" +
                    "环境：" + active;
            javaMailSender.send(new SendMailUtil().sendIdentifyingCode("订购套餐结果异常", sendText));
            log.info(callback.getDeviceCode() + ":【新订|续订】回调异常邮件发送成功");

        } catch (MailException e) {
            log.info("【新订|续订】回调异常邮件发送出现异常：" + e);
        }
    }

    /***
     * 发送异常邮件
     * 回调异常发到1556723929@qq.com
     * @param callbackStr
     * @param message
     */
    public void sendToPrivate(String callbackStr, String message) {
        try {
            String sendText = "【新订|续订的回调】内容：" + callbackStr + "\n" +
                    "异常描述:" + message + "\n" +
                    "环境：" + active;
            javaMailSender.send(new SendMailUtil().sendMailToPrivate("【新订|续订的回调】处理异常", sendText));
            log.info("【新订|续订的回调】异常邮件发送成功");

        } catch (MailException e) {
            log.info("【新订|续订的回调】邮件发送出现异常：" + e);
        }
    }

    /***
     * 订购，续订套餐出现异常
     * （取消/结束订单）异常发到service@linksfield.net
     * @param deviceCode
     * @param packageName
     * @param orderId
     * @param type
     * @param message
     */
    public void sendMail(String deviceCode, String packageName, String orderId, String type, String message) {
        try {

            String sendText = "卡片iccId:" + deviceCode + "\n" +
                    "套餐名称:" + packageName + "\n" +
                    "订单编码:" + orderId + "\n" +
                    "操作类型:" + type + "\n" +
                    "异常描述:" + message + "\n" +
                    "环境：" + active;
            javaMailSender.send(new SendMailUtil().sendIdentifyingCode("赠送套餐处理异常", sendText));
            log.info(orderId + ":（取消/结束订单）异常邮件发送成功");

        } catch (MailException e) {
            log.info("（取消/结束订单）邮件发送出现异常：" + e);
        }
    }


    /***
     * 发送异常邮件
     * 新订/续订异常发到1556723929@qq.com
     * @param deviceCode
     * @param packageName
     * @param type
     * @param message
     */
    public void sendMailToPrivate(String deviceCode, String packageName, String type, String message) {
        try {
            String sendText = "卡片iccId:" + deviceCode + "\n" +
                    "套餐名称:" + packageName + "\n" +
                    "操作类型:" + type + "\n" +
                    "异常描述:" + message + "\n" +
                    "环境：" + active;
            javaMailSender.send(new SendMailUtil().sendMailToPrivate("新订/续订处理异常", sendText));
            log.info(deviceCode + ":（新订/续订）异常邮件发送成功");

        } catch (MailException e) {
            log.info("（新订/续订）邮件发送出现异常：" + e);
        }
    }

    /***
     * 按照时间从最早到最晚将订单排序
     * @param rList
     * @return
     */
    public List<H5PackageOrder> sort(List<H5PackageOrder> rList) {

        Collections.sort(rList, new Comparator<H5PackageOrder>() {
            @Override
            public int compare(H5PackageOrder o1, H5PackageOrder o2) {
                Date date1 = null;
                Date date2 = null;
                try {
                    date1 = new SimpleDateFormat(StringOutputConstant.CODE_DATE).parse(o1.getOrderDate());
                    date2 = new SimpleDateFormat(StringOutputConstant.CODE_DATE).parse(o2.getOrderDate());
                } catch (ParseException e) {
                    log.info("时间转换发生了异常：" + e);
                }
                if (date1.after(date2)) {
                    return 1;
                } else if (date2 == date1) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });
        return rList;
    }

    /***
     *
     * 异常信息入库
     *
     * 表名：user_order_exception_record_t
     *
     * @param partnerCode
     * @param deviceCode
     * @param payId
     * @param excpLocation
     * @param retCode
     * @param resultInfo
     */
    public void ExceptionRecord(String partnerCode, String deviceCode, String payId, String excpLocation, String retCode, String resultInfo) {

        OrderExceptionRecord record = new OrderExceptionRecord();
        record.setPartnerCode(partnerCode);
        record.setDeviceCode(deviceCode);
        record.setPayId(payId);
        record.setExcpLocation(excpLocation);
        record.setRetCode(retCode);
        record.setResultInfo(resultInfo);
        purchaseMapper.storageExceptionRecord(record);
    }


    /***
     *根据设备号（ICCID）查询订阅邮箱
     * @param deviceCode
     * @return
     */
    public String queryEmail(String deviceCode) {

        return purchaseMapper.queryEmail(deviceCode);
    }

    /**
     * 查询套餐编码是否存在于赠送套餐列表
     *
     * @param packageCode
     * @return
     */
    public Integer queryGiveDateOrNot(String packageCode) {

        return purchaseMapper.queryGiveDateOrNot(packageCode);
    }
}
